package com.xmscltd.scms.admin.controller.system;

import com.jfinal.core.paragetter.Para;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.xmscltd.scms.base.common.RestResult;
import com.xmscltd.scms.base.model.Res;
import com.xmscltd.scms.base.rest.select2.BootstrapSelect2;
import com.xmscltd.scms.base.service.ResService;
import com.xmscltd.scms.base.web.base.BaseController;
import io.jboot.component.swagger.ParamType;
import io.jboot.core.rpc.annotation.JbootrpcService;
import io.jboot.web.controller.annotation.RequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * department
 * com.xmscltd.scms.admin.controller.system
 * Created with IntelliJ IDEA.
 * Description:
 * Author: Administrator-cmchen
 * Date: 2018-04-15
 * Time: 17:13
 * Version: V1.0.0
 */
@RequestMapping("/system/res")
@Api(description = "菜单管理", basePath = "/system/res", tags = "菜单管理接口")
public class ResController extends BaseController {

    @JbootrpcService
    private ResService resService;

    public void index() {
        render("main.html");
    }

    /**
     * 获取部门列表Controller
     */
    public void getResTree() {
        renderJson(getTreeList(0, null, null));
    }

    /**
     * 构建jsTree 部门树
     *
     * @param tid     顶层id
     * @param listmap
     * @param list
     * @return
     */
    private List getTreeList(Integer tid, List<Map<String, Object>> listmap, List<Res> list) {

        //获取所有的部门
        if (listmap == null || list == null) {
            list = resService.findAll();
            listmap = new ArrayList<Map<String, Object>>();
            for (Res d : list) {
                if (d.getPid() == 0) {
                    //如果上级部门 ==0 ，没有父节点
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("id", d.getId().toString());
                    map.put("name", d.getName());
                    map.put("icon", d.getIconCls());
                    listmap.add(map);
                }
            }
            getTreeList(tid, listmap, list);

        } else if (listmap.size() > 0 && list.size() > 0) {
            for (Map<String, Object> mp : listmap) {
                String id = (String)mp.get("id");
                String pid = null;
                List<Map<String, Object>> childlist = new ArrayList<Map<String, Object>>();
                for (Res d : list) {
                    pid = d.getPid() + "";
                    //遍历子部门放到children
                    if (id.equals(pid)) {
                        Map<String, Object> m = new HashMap<String, Object>();
                        m.put("id", d.getId().toString());
                        m.put("name", d.getName());
                        m.put("icon", d.getIconCls());
                        childlist.add(m);
                    }
                }
                //如果存在children  放到map中
                if (childlist.size() > 0) {
                    List<String> sizelist = new ArrayList<String>();
                    sizelist.add(childlist.size() + "");
                    mp.put("children", childlist);
                    mp.put("tags", sizelist);
                    getTreeList(tid, childlist, list);
                }
            }
        }
        return listmap;
    }

    /**
     * 获取部门列表Controller
     */
    public void getResList() {
        List<Res> list = resService.findAll();
        renderJson(list);
    }

    /**
     * 部门详情
     */
    public void getResDetail() {
        int id = getParaToInt("id");
        Res res = resService.findById(id);
        renderJson(res);
    }


    /**
     * 选择上级部门时搜索部门列表
     */
    @ApiOperation(value = "获取菜单列表", httpMethod = "GET",
            notes = "获取菜单列表,搜索参数q")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "queryParm 搜索内容",
                    paramType = ParamType.QUERY, dataType = "string", required = false)
    })
    public void getResPage() {
        String queryParm = getPara("q");
        String page = getPara("page");
        String whereStr = getPara("id");
        int pageNumber = 1;
        if (StrKit.notBlank(page)) {
            pageNumber = Integer.parseInt(page);
        }
        Page<Res> list = resService.findPage(queryParm, pageNumber, 15, whereStr);
        renderJson(new BootstrapSelect2<Res>(list));
    }

    /**
     * 更新新增部门
     *
     * @param res
     */
    @ApiOperation(value = "更新或者新增菜单", httpMethod = "POST", notes = "更新或者新增菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Res field", value = "菜单对象字段可使用?status=1&type=1...测试接口",
                    paramType = ParamType.FORM, dataType = "string", required = true)
    })
    public void addOrUpdate(@Para("") Res res) {
        RestResult<String> restResult = new RestResult<String>();
        Long pid = res.getPid();
        
        if( pid == 0){ //do not have pid  level=1
        	res.setLevel(1);
        }else if(pid != 0 && res.getType().endsWith("1")){ //hava pid and type==1 ,level=2
        	res.setLevel(2);
        }else{ // level=3
        	res.setLevel(3);
        }
        
        if (res.getId() == null) {  //new Res ?save
            resService.save(res);
            restResult.success().setMsg("保存成功");
        } else { //else update Res
            restResult.success().setMsg("更新成功");
            resService.update(res);
        }
        renderJson(restResult);
    }

    public void delete(@Para("") Res res){
        RestResult<String> restResult = new RestResult<String>();
        resService.delete(res);
        restResult.success().setMsg("保存成功");
    }
}
